/************************************
 * INIT
 ************************************/
var delPrefix = "del"; // used to build element ids like "del0,del1,.."
var markedForRemoval = [];
var urls = [];
var colors = [];

function init() {
    _e("btnApply").value = chrome.i18n.getMessage("manager_apply");
    _e("btnCancel").value = chrome.i18n.getMessage("manager_cancel");
    _e("sortby").innerText = chrome.i18n.getMessage("manager_sort")+" : ";
    
    // extracting keys and values from localStorage
    for (var i=0,len=localStorage.length; i<len; i++){
        var key = localStorage.key(i);
        urls.push(key);
        colors.push(localStorage[key]);
    }
    
    // display table
    disp();
}

/************************************
 * EVENTS
 ************************************/
function btnApply_Click() {
    removeMarked();
    window.close();
}

function btnCancel_Click() {
    window.close();
}

/************************************
 * METHODS
 ************************************/
function removeMarked() {
    var markedUrls = [];
    for (var i=0; i<markedForRemoval.length; i++) {
        // undo = undefined
        if (markedForRemoval[i] != undefined) {
            markedUrls.push(urls[markedForRemoval[i]]);
        }
    }
    markedUrls = markedUrls.join(",");
    
    chrome.extension.sendRequest({
        cmd:"batchRemove",
        links: markedUrls
    }, function(response) {
        // update tags on current page
      // TODO : callback doesn't work yet...
        /// Sends [cmd] to content script
        chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendRequest(tab.id, {
                cmd: "updateTags"
            });
        });
    });
}
 
function markForRemoval(sender) {
    var id = sender.id.substring(delPrefix.length);
    markedForRemoval.push(id);
    sender.style.color = "#aaaaaa";
    sender.innerHTML = chrome.i18n.getMessage("manager_undo_char");
    sender.title = chrome.i18n.getMessage("manager_undo_title");
    sender.onclick = function() {
        unmarkForRemoval(sender);
    };
    
    if (_e("btnApply").disabled != "") {
        _e("btnApply").disabled = "";
    }
}

function unmarkForRemoval(sender) {
    var id = sender.id.substring(delPrefix.length);
    var i=0;
    var b = false;
    while (i<markedForRemoval.length && !b) {
        if (markedForRemoval[i] == id) {
            b = true;
            delete markedForRemoval[i]; // delete id in array, so it will not be deleted
            sender.style.color = "";
            sender.innerHTML = chrome.i18n.getMessage("manager_del_char");
            sender.title = chrome.i18n.getMessage("manager_del_title");
            sender.onclick = function() {
                markForRemoval(sender);
            };
        }
        i++;
    }
}

function sortByDate() {
    alert(chrome.i18n.getMessage("err_not_implemented"));
}

function sortByUrl() {
    alert(chrome.i18n.getMessage("err_not_implemented"));
}

function sortByColor() {
    alert(chrome.i18n.getMessage("err_not_implemented"));
}

function disp() {
    var content = ["<table>"];
    if (urls.length > 0) {
        for (var i=0; i<urls.length; i++) {
            var append = [
                "<tr>",
                "   <td><a class='del' id='",delPrefix,i,"' title='",chrome.i18n.getMessage("manager_del_title"),"' onclick='markForRemoval(this)'>x</a></td>",
                "   <td><div class='square' style='background-color:",colors[i],";' title='",colors[i],"'></div></td>",
                "   <td><a class='url' href='#' onclick='redirectCurrentPageToUrl(\"",urls[i],"\")'>",urls[i],"</a></td>",
                "</tr>"
            ].join("");
            content.push(append);
        }
        content.push("</table>");
        _e("tags").innerHTML = content.join("");
    } else {
        _e("tags").innerHTML = chrome.i18n.getMessage("manager_nothing");
    }
}

/************************************
 * UTILS
 ************************************/
function redirectCurrentPageToUrl(url) {
    // Sends [cmd, redirectUrl] to content script
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {
            cmd: "redirectToUrl",
            redirectUrl: url
        });
    });
}
 
function _e(id) {
    return document.getElementById(id);
}
